new Vue({
    el: "#app",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            // 商品签收表格數據
            commoditySignGroupList: [],
            // 多選框選中數據
            selectRows: [],
            // 商品列表
            commodityList: [],
            // 商品類型列表
            commodityTypeList: [],
            // 商品類別樹數據
            commodityTypesTree: [],
            // 弹出层标题
            title: "",
            // 是否显示訂單主記錄
            openOrderMainList: false,
            // 是否显示訂單子記錄
            openDtl: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                blcId: null,
                fId: null,
                stoId: null,
                dtStaffNo: "",
                csState: undefined,
                actId: undefined,
                acId: undefined,
            },
            balconies: [],
            floors: [],
            storages: [],
            beds: [],
            orderMainList: [], // 訂單主記錄集合
            comStateOptions: [],
            orderDtls: [], // 訂單子記錄
            orderChoose: {}, // 選擇的訂單
            selection:[], // 多選框選中的表格
            userInfo: {}, // 用戶信息
            fingerLoading: undefined, // 指纹识别加载层
            verifyTimingMax: 10, // 指紋驗證超時時間
            verifyTiming: 0, // 當前指紋驗證時間
            verifyTimer: null // 指紋驗證定時器
        };
    },
    watch: {
        "queryParams.actId": {
            handler(v) {
                this.$set(this.queryParams, "acId", undefined);
            },
        },
        "queryParams.acId": {
            handler(v) {
                this.getList();
            },
        },
        "queryParams.dtStaffNo":{
            handler(vNew,vOld){
                if(vNew && vNew.length === 3 && vNew.length > vOld.length){
                    this.queryParams.dtStaffNo += "/"
                }
            }
        }
    },
    computed: {
        commoditySignGroupListFilter() {
            let list = JSON.parse(JSON.stringify(this.commoditySignGroupList));
            if (this.queryParams.dtStaffNo) {
                list = list.filter(
                    (d) => d.dtStaffNo.indexOf(this.queryParams.dtStaffNo) > -1
                );
            }
            if (this.queryParams.blcId) {
                list = list.filter(
                    (s) =>
                        s.dtDtoNo &&
                        Number(s.dtDtoNo.split("-")[0]) === this.queryParams.blcId
                );
            } else {
                this.queryParams.fId = this.queryParams.stoId = null;
            }
            if (this.queryParams.fId) {
                list = list.filter(
                    (s) => Number(s.dtDtoNo.split("-")[1]) === this.queryParams.fId
                );
            } else {
                this.queryParams.stoId = null;
            }
            if (this.queryParams.stoId) {
                list = list.filter(
                    (s) => Number(s.dtDtoNo.split("-")[2]) === this.queryParams.stoId
                );
            }
            this.total = list.length;
            return list.slice(
                (this.queryParams.pageNum - 1) * this.queryParams.pageSize,
                this.queryParams.pageNum * this.queryParams.pageSize
            );
        },
    },
    created() {
        this.loading = true
        const userInfo = localStorage.getItem('userInfo')
        if(!userInfo) {
            location.href = '../login.html'
            return
        }
        this.userInfo = JSON.parse(userInfo)
        userLogin(this.userInfo).then(res => {
            if (res.code === 200) {
                listDto(["balconies", "floors", "storages", "beds"]).then((res) => {
                    const dto = res.data;
                    this.balconies = dto.balconies;
                    this.floors = dto.floors;
                    this.storages = dto.storages;
                    this.beds = dto.beds;
                    this.getList();
                });
                listCommodity().then((res) => {
                    this.commodityList = res.data;
                });
                listCommodityType().then((response) => {
                    const commodityTypeList = response.data;
                    this.commodityTypeList = JSON.parse(JSON.stringify(commodityTypeList));
                    const treeData = [];
                    commodityTypeList
                        .filter((t) => t.actPId === -1)
                        .forEach((t) => {
                            t.children = commodityTypeList.filter((_t) => _t.actPId === t.actId);
                            t.hasChildren = t.children > 0;
                            treeData.push(t);
                        });
                    this.commodityTypesTree = treeData;
                });
                this.loading = false
                this.comStateOptions = [
                    {
                        dictLabel:"待確認",
                        dictValue:"0",
                    },
                    {
                        dictLabel:"配貨中",
                        dictValue:"1",
                    },
                    {
                        dictLabel:"取消貨物",
                        dictValue:"2",
                    }
                ];
                this.csStateOptions = [
                    {
                        dictLabel:"未簽收",
                        dictValue:"0",
                    },
                    {
                        dictLabel:"已簽收",
                        dictValue:"1",
                    },
                    {
                        dictLabel:"缺貨",
                        dictValue:"2",
                    }
                ];
            }
        }).catch(() => {
            this.loading = false
            location.href = '../login.html'
        })
    },
    methods: {
        changeSelection(selection){
            this.selection = selection;
        },
        canSelect(row){
            return row.csState === 0 && row.csDeleteState === 0
        },
        // 回显数据字典
        selectDictLabel(datas, value) {
            var actions = [];
            Object.keys(datas).map((key) => {
                if (datas[key].dictValue === ('' + value)) {
                    actions.push(datas[key].dictLabel);
                    return false;
                }
            })
            return actions.join('');
        },
        handleSelectionChange(rows) {
            this.selectRows = rows;
        },
        // 訂單子項狀態字典翻译
        comStateFormat(row, column) {
            return this.selectDictLabel(this.comStateOptions, row.comState);
        },
        // 簽收狀態字典翻译
        csStateFormat(row) {
            return this.selectDictLabel(this.csStateOptions, row.csState);
        },
        /** 獲取囚倉資料名稱 */
        getDtoName(row) {
            const dtDtoNo = row.dtDtoNo;
            let dtoNames = [];
            if (dtDtoNo) {
                const dtoNos = dtDtoNo.split("-");
                if (dtoNos[0]) {
                    const blc = this.balconies.find(
                        (blc) => blc.blcId === Number(dtoNos[0])
                    );
                    dtoNames.push(blc ? blc.blcName : "未知樓座");
                }
                if (dtoNos[1]) {
                    const floor = this.floors.find((f) => f.fId === Number(dtoNos[1]));
                    dtoNames.push(floor ? floor.fName : "未知樓層");
                }
                if (dtoNos[2]) {
                    const sto = this.storages.find((s) => s.stoId === Number(dtoNos[2]));
                    dtoNames.push(sto ? sto.stoName : "未知囚倉");
                }
                if (dtoNos[3]) {
                    const bed = this.beds.find((b) => b.bId === Number(dtoNos[3]));
                    dtoNames.push(bed ? bed.bNo : "未知床位");
                }
                return dtoNames.join("/");
            } else {
                return "暫無";
            }
        },
        showSignGroupDtl(row) {
            this.loading = true;
            listMainTemplate({dtStaffNo: row.dtStaffNo, comState: 1}).then(
                (res) => {
                    this.loading = false;
                    if (res.code === 200) {
                        const orderMainList = res.data;
                        if (orderMainList && orderMainList.length) {
                            this.orderMainList = orderMainList;
                            this.openOrderMainList = true;
                        } else {
                            this.msgError("未查詢到該囚犯的配貨中訂單記錄");
                        }
                    }
                }
            );
        },

        /** 查詢訂單子項 */
        showDtl(row) {
            this.orderChoose = row;
            this.loading = true;
            listCommoditySignTemplate({comId: row.comId}).then((res) => {
                this.orderDtls = res.data;
                this.openDtl = true;
                this.loading = false;
            });
        },
        /** 查询商品签收列表 */
        getList() {
            // this.queryParams = {
            //     ...this.queryParams,
            //     pageNum: 1,
            //     pageSize: 10,
            //     blcId: null,
            //     fId: null,
            //     stoId: null,
            //     dtStaffNo: "",
            // };
            this.queryParams.pageNum = 1
            this.loading = true;
            if (this.queryParams.acId) {
                listGroupByAcId(this.queryParams).then((response) => {
                    this.commoditySignGroupList = response.data;
                    this.total = response.data.length;
                    this.loading = false;
                });
            } else {
                listGroup(this.queryParams).then((response) => {
                    this.commoditySignGroupList = response.data;
                    this.total = response.data.length;
                    this.loading = false;
                });
            }
        },

        updateSignDtlState(row, option) {
            this.loading = true;
            updateSignDtlState({
                csId: row.csId,
                option,
            })
                .then((res) => {
                    if (res.code === 200) {
                        this.msgSuccess(res.msg);
                        listCommoditySignTemplate({comId: row.comId}).then((res) => {
                            this.orderDtls = res.data;
                            this.loading = false;
                            this.getList();
                        });
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },

        // 指紋識別測試
        fingerprintRecognizeTest() {
            !this.fingerLoading && (this.fingerLoading = this.$loading({
                lock: true,
                text: '請驗證指紋',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            }))
            fingerprintRecognize().then(res => {
                if (res.code === 500) {
                    this.$message.error("請抬起手指，重新按壓指紋");
                    this.fingerprintRecognizeTest()
                } else if (res.code === 200) {
                    const id = res.data.id
                    let staffNo = parseInt(id / 10) + ''
                    const length = staffNo.length
                    for (let i = 0; i < 7 - length; i++) {
                        staffNo = '0' + staffNo
                    }
                    staffNo = staffNo.slice(0, 3) + '/' + staffNo.slice(3)
                    this.fingerLoading.close()
                    this.fingerLoading = undefined
                    this.$confirm("識別出的編號為：" + staffNo, "提示", {
                        confirmButtonText: "確定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                }
            })
        },
        fingerprintRecognize (item) {
            if(!this.fingerLoading) {
                return
            }
            fingerprintRecognize().then(res => {
                if (res.code === 500) {
                    this.$message.error("請抬起手指，重新按壓指紋");
                    this.fingerprintRecognize(item)
                } else if (res.code === 200) {
                    const id = res.data.id
                    let staffNo = parseInt(id / 10) + ''
                    const length = staffNo.length
                    for (let i = 0; i < 7 - length; i++) {
                        staffNo = '0' + staffNo
                    }
                    staffNo = staffNo.slice(0, 3) + '/' + staffNo.slice(3)
                    if(item) {
                        if(staffNo !== item.dtStaffNo) {
                            this.$message.error("請抬起手指，重新按壓指紋");
                            this.fingerprintRecognize(item)
                            return
                        }
                        this.$message.success('指紋驗證成功')
                        clearInterval(this.verifyTimer)
                        if(this.fingerLoading) {
                            this.fingerLoading.close();
                            this.fingerLoading = undefined
                        }
                        sign(item).then(res => {
                            if(res.code === 200){
                                this.$refs.signTable.clearSelection();
                                this.$message.success("簽收成功");
                                listCommoditySignTemplate({comId: item.comId}).then((res) => {
                                    this.orderDtls = res.data
                                    this.loading = false
                                    this.getList()
                                })
                            }
                        },rej => {
                            this.fingerLoading.close();
                            this.fingerLoading = undefined
                        })
                    } else {
                        if(staffNo !== this.selection[0].dtStaffNo) {
                            this.$message.error("請抬起手指，重新按壓指紋");
                            this.fingerprintRecognize(item)
                            return
                        }
                        clearInterval(this.verifyTimer)
                        if(this.fingerLoading) {
                            this.fingerLoading.close();
                            this.fingerLoading = undefined
                        }
                        const comId = this.selection[0].comId
                        signAll(this.selection).then(res => {
                            if(res.code === 200){
                                this.$message.success("簽收成功");
                                this.$refs.signTable.clearSelection();
                                listCommoditySignTemplate({comId}).then((res) => {
                                    this.orderDtls = res.data;
                                    this.loading = false;
                                    this.queryParams.dtStaffNo = undefined
                                    this.openDtl = false
                                    this.getList();
                                });
                            }
                        },rej => {
                            this.fingerLoading.close();
                            this.fingerLoading = undefined
                        })
                    }
                }
            })
        },
        /** 簽收 */
        sign(item,type){
            this.$confirm("是否確认簽收該商品?", "警告", {
                confirmButtonText: "確定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                switch (type) {
                    case 1:
                        !this.fingerLoading && (this.fingerLoading = this.$loading({
                            lock: true,
                            text: '請驗證指紋',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        }));
                        this.verifyTiming = 0
                        this.verifyTimer = setInterval(() => {
                            this.verifyTiming += 1
                            if(this.verifyTiming >= this.verifyTimingMax) {
                                clearInterval(this.verifyTimer)
                                if(this.fingerLoading) {
                                    this.fingerLoading.close();
                                    this.fingerLoading = undefined
                                }
                            }
                        },1000)
                        this.fingerprintRecognize(item)
                        break;
                    case 2:
                        this.$prompt("指紋驗證超時，如確認是由本人簽收，請驗證輸入您的工作號進行簽收確認操作", "提示", {
                            confirmButtonText: "確定",
                            cancelButtonText: "取消",
                            closeOnClickModal: false
                        }).then(({ value }) => {
                            if(value !== this.userInfo.couPoliceNo) {
                                this.$message.error('工作證號驗證失敗')
                                return
                            }
                            this.loading = true
                            sign(item).then(res => {
                                if(res.code === 200){
                                    this.$refs.signTable.clearSelection();
                                    this.$message.success("簽收成功");
                                    listCommoditySignTemplate({comId: item.comId}).then((res) => {
                                        this.orderDtls = res.data
                                        this.getList()
                                    })
                                }
                            },rej => {
                                this.loading = false
                            })
                        }).catch(() => {})
                        break;
                    case 3:
                        sign(item).then(res => {
                            this.loading = true
                            if(res.code === 200){
                                this.$refs.signTable.clearSelection();
                                this.$message.success("簽收成功");
                                listCommoditySignTemplate({comId: item.comId}).then((res) => {
                                    this.orderDtls = res.data
                                    this.getList()
                                })
                            }
                        },rej => {
                            this.loading = false
                        })
                        break;
                }
            })
        },
        /** 一鍵簽收 */
        signAll(type){
            this.$confirm("是否確认簽收選中的商品?", "警告", {
                confirmButtonText: "確定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                switch (type) {
                    case 1:
                        this.fingerLoading = this.$loading({
                            lock: true,
                            text: '請驗證指紋',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        this.verifyTiming = 0
                        this.verifyTimer = setInterval(() => {
                            this.verifyTiming += 1
                            if(this.verifyTiming >= this.verifyTimingMax) {
                                clearInterval(this.verifyTimer)
                                if(this.fingerLoading) {
                                    this.fingerLoading.close();
                                    this.fingerLoading = undefined
                                }
                            }
                        },1000)
                        this.fingerprintRecognize()
                        break;
                    case 2:
                        this.$prompt("指紋驗證超時，如確認是由本人簽收，請驗證輸入您的工作號進行簽收確認操作", "提示", {
                            confirmButtonText: "確定",
                            cancelButtonText: "取消",
                            closeOnClickModal: false
                        }).then(({ value }) => {
                            if(value !== this.userInfo.couPoliceNo) {
                                this.$message.error('工作證號驗證失敗')
                                return
                            }
                            this.loading = true
                            const comId = this.selection[0].comId
                            signAll(this.selection).then(res => {
                                if(res.code === 200){
                                    this.$message.success("簽收成功");
                                    this.$refs.signTable.clearSelection();
                                    listCommoditySignTemplate({comId}).then((res) => {
                                        this.orderDtls = res.data;
                                        this.queryParams.dtStaffNo = undefined
                                        this.openDtl = false
                                        this.getList();
                                    });
                                }
                            },rej => {
                                this.loading = false;
                            })
                        }).catch(() => {})
                        break;
                    case 3:
                        this.loading = true
                        const comId = this.selection[0].comId
                        signAll(this.selection).then(res => {
                            if(res.code === 200){
                                this.$message.success("簽收成功");
                                this.$refs.signTable.clearSelection();
                                listCommoditySignTemplate({comId}).then((res) => {
                                    this.orderDtls = res.data;
                                    this.queryParams.dtStaffNo = undefined
                                    this.openDtl = false
                                    this.getList();
                                });
                            }
                        },rej => {
                            this.loading = false;
                        })
                        break;
                }
            })
        },
        /** 一鍵簽收所選囚犯的指定商品 */
        signSelection() {
            this.$confirm("是否確认簽收選中囚犯的指定商品?", "警告", {
                confirmButtonText: "確定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$prompt("如確認是由本人簽收，請驗證輸入您的工作號進行簽收確認操作", "提示", {
                    confirmButtonText: "確定",
                    cancelButtonText: "取消",
                    closeOnClickModal: false
                }).then(({ value }) => {
                    if(value !== this.userInfo.couPoliceNo) {
                        this.$message.error('工作證號驗證失敗')
                        return
                    }
                    this.loading = true
                    signAll(this.selectRows).then(res => {
                        if(res.code === 200){
                            this.$message.success("簽收成功");
                            this.getList();
                        }
                    },rej => {
                        this.loading = false;
                    })
                }).catch(() => {})
            })
        },
        /** 修改簽收數量 */
        editSignCount(row) {
            this.$prompt('請輸入簽收數量', '提示', {
                confirmButtonText: '確定',
                cancelButtonText: '取消',
                inputPattern: /\d/,
                inputErrorMessage: '請輸入合法的數字'
            }).then(({ value }) => {
                const newCount = parseInt(value)
                if(newCount > row.csOrderCount) {
                    this.$message.error('簽收數量不可高於下單數量')
                    return;
                }
                this.loading = true
                updateSignCount({csId: row.csId, csSignCount: newCount}).then(res => {
                    if(res.code === 200) {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                        listCommoditySignTemplate({comId: row.comId}).then((res) => {
                            this.orderDtls = res.data
                            this.loading = false
                            this.getList()
                        })
                        this.loading = false
                    }
                }).catch(() => {
                    this.loading = false
                })
            })
        },
        /** 登出 */
        logout() {
            localStorage.removeItem('userInfo')
            location.href = '../login.html'
        },
        /** 设置尾行不同颜色 */
        rowStyleFunction({rowIndex}) {
            const style = {}
            if(rowIndex === this.orderDtls.length - 1) {
                style.backgroundColor = "rgb(198, 226, 255)"
            }
            return style
        },
        /** 重新同步指紋信息 */
        restartDevice() {
            this.$confirm("是否確认重新錄入指紋信息?", "警告", {
                confirmButtonText: "確定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(res => {
                this.loading = true
                restartDevice().then(res => {
                    if(res === 'OK') {
                        this.loading = false
                        this.$message.success('指紋重新錄入成功')
                    }
                }).catch(() => {
                    this.loading = false
                    this.$message.error('指紋重新錄入失敗')
                })
            })
        }
    },
})